import React, { PureComponent,Fragment } from "react";
import { connect } from "dva";
import router from 'umi/router';
import { Row, Col, Form, Card, Input,  Icon, Button, message, TreeSelect } from "antd";


const FormItem = Form.Item;
const { TextArea } = Input;

function fn(data, pid) {
  let result = [], temp;
  if(data && pid) {
    for (let i in data) {
      if (data[i].parentId == pid) {
        result.push(data[i]);
        temp = fn(data, data[i].districtId);
        if (temp.length > 0) {
          data[i].children = temp;
        }
      }
    }
  }
  return result;
}

Array.prototype.ToTreeJson = function (pid) {
  let result = [], temp;
  for (let i in this) {
    if (this[i].parentId == pid) {
      result.push(this[i]);
      temp = fn(this, this[i].districtId);
      if (temp.length > 0) {
        this[i].children = temp;
      }
    }
  }
  return result;
}

const treeDataFun = data =>{
  return data.map(item=>{
    if(item.children){
      return {children:treeDataFun(item.children),key:`${item.districtId}`,value:`${item.districtId}`, title:item.districtName};
    }else{
      return {key:`${item.districtId}`,value:`${item.districtId}`, title:item.districtName};
    }
  })
}

@connect(({ district }) => ({
  resdata: district.resdata,
  loading:district.loading,
  // loading: loading.models.equipment_integrated,
}))
@Form.create()
export default class NoticeAdd extends PureComponent {
  constructor(props) {
    super(props);
    this.detailInfoId = this.props.match.params.id && this.props.match.params.id!='detail' ? this.props.match.params.id : 0;
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'district/fetch_district_list',
    });

  }




  handleFormSubmit(e)  {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { dispatch } = this.props;
        const action = this.detailInfoId!=0 ? 'edit' : 'add';
        const districtId = this.detailInfoId!=0 ? this.detailInfoId : undefined;
        if(values.parentId==undefined){
          values.parentId = "0";
        }
        dispatch({
          type: `district/${action}_district`,
          payload: {
            ...values,
            districtId
          }
        }).then(() => {
            this.handleReset();
            message.success(this.detailInfoId!=0 ? "区域信息已修改" : "区域已添加");
            if(this.detailInfoId!=0){
              this.goBack();
            }else{
              router.push({ pathname:`/system/district/list`});
            }
        });
      }
    });
  }

  handleReset = () => {
    this.props.form.resetFields();
  };


  goBack = () => {
    const { dispatch, location } = this.props;
    router.push({ pathname:`/system/district/list`,  query: { ...location.query} });
  }


  render() {
    const {  loading, resdata } = this.props;
    const { getFieldDecorator } = this.props.form;

    const detaildata = resdata.list.find(item=>item.districtId==this.detailInfoId);
    // console.log(detaildata)
    const treeData=treeDataFun(resdata.list.ToTreeJson(0));

    return (
       <Card
             bodyStyle={{padding:'50px 100px'}}
       >
            <Form layout="horizontal">
              <Row gutter={24}>
                <Col span={8}>
                  <FormItem label="区域编号">
                    {getFieldDecorator("districtCode", {
                      initialValue: this.detailInfoId === 0 ? undefined : detaildata && detaildata.districtCode,
                      rules: [
                        {
                          required: true,
                          message: "请输入区域编号"
                        }
                      ]
                    })(<Input placeholder="请输入区域编号" />)}
                  </FormItem>
                </Col>

                <Col span={8}>
                  <FormItem label="区域名称">
                    {getFieldDecorator("districtName", {
                      initialValue: this.detailInfoId === 0 ? undefined : detaildata && detaildata.districtName,
                      rules: [
                        {
                          required: true,
                          message: "请输入区域名称"
                        }
                      ]
                    })(<Input placeholder="请输入区域名称" />)}
                  </FormItem>
                </Col>

                <Col span={8}>
                  <FormItem label="上级区域">
                    {getFieldDecorator("parentId", {
                      // initialValue: this.detailInfoId === 0 ? undefined : detaildata && detaildata.parentId,
                      initialValue:this.detailInfoId === 0 ? undefined : detaildata && String(detaildata.parentId) && String(detaildata.parentId)!=0 ? String(detaildata.parentId) : undefined,
                      // rules: [
                      //   {
                      //     required: true,
                      //     message: "请选择上级部门"
                      //   }
                      // ]
                    })(
                      <TreeSelect
                        dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                        treeData={treeData}
                        allowClear={true}
                        placeholder="请选择上级区域"
                        treeDefaultExpandAll
                        // onChange={this.onTreeSelectChange}
                      />
                    )}
                  </FormItem>
                </Col>

                <Col span={24}>
                  <FormItem label="备注" >
                    {getFieldDecorator("remarks", {
                      initialValue: this.detailInfoId === 0 ? undefined : detaildata && detaildata.remarks,
                      rules: [{ max: 200, message: "不超过200个字" }]
                    })(
                      <TextArea
                        placeholder="请输入备注内容"
                        autosize={{ minRows: 3, maxRows: 6 }}
                      />
                    )}
                  </FormItem>
                </Col>

                {/*

                <Col span={8}>
                  <FormItem label="排序">
                    {getFieldDecorator("sort", {
                      initialValue: this.detailInfoId === 0 ? 0 : detaildata && detaildata.sort,
                    })(<InputNumber placeholder="请输入" precision={0}   />)}
                  </FormItem>
                </Col>


                */}


              </Row>



              <Row gutter={24} >
                <Col span={24} style={{textAlign:'center',padding:30}}>
                    <Button
                      onClick={this.handleFormSubmit.bind(this)}
                      type="primary"
                      size="large"
                      style={{marginRight:15}}
                      loading={loading.add}
                    >
                      提交
                    </Button>
                    <Button
                      onClick={this.handleReset.bind(this)}
                      type="default"
                      size="large"
                    >
                      重置
                    </Button>
                </Col>
              </Row>
            </Form>



       </Card>
    );
  }
}
